package org.squabble.web.admin;

import java.util.Map;

import javax.annotation.security.RolesAllowed;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.squabble.SquabbleConstants;
import org.squabble.domain.SystemProperty;
import org.squabble.service.SystemService;

@Controller
@RequestMapping("/admin/system/email")
public class SystemEmailController extends AbstractSystemController {

	@Autowired
	SystemService systemService;

	@RequestMapping(method = RequestMethod.GET)
	public String setupForm(ModelMap modelMap) {
		SystemEmailCommand sc = new SystemEmailCommand();
		Map<String, SystemProperty> props = systemService
				.getSystemPropertyMap();
		sc.setEmailSMTPServer(props.get("emailSMTPServer").getValue()
				.toString());
		sc.setEmailUser(props.get("emailUser").getValue().toString());
		sc.setEmailPassword(props.get("emailPassword").getValue().toString());
		sc.setEmailAddress(props.get("emailAddress").getValue().toString());
		sc.setEmailUseTLS((Boolean) getPropertyValue(props, "emailUseTLS"));
		sc.setEmailUseSSL((Boolean) getPropertyValue(props, "emailUseSSL"));
		sc.setEmailSMTPPort((Long) getPropertyValue(props, "emailSMTPPort"));

		modelMap.addAttribute("systemEmailCommand", sc);
		return "admin.system.email";
	}

	@RolesAllowed("ROLE_ADMIN")
	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(ModelMap map,
			@ModelAttribute("systemEmailCommand") SystemEmailCommand sc) {
		systemService.updateEmailProperties(sc);
		map.addAttribute(SquabbleConstants.POST_PROCESS_MESSAGE,
				"system.processed");
		return "redirect:/admin/system/email";
	}

}
